<?php

declare (strict_types=1);

namespace app\store\model\dealer;

use app\common\model\dealer\Order as OrderModel;

/**
 * 分销商订单模型
 * Class Order
 * @package app\store\model\dealer
 */
class Order extends OrderModel
{
    /**
     * 获取分销商订单列表
     * @param array $param
     * @return iterable|\think\model\Collection|\think\Paginator
     */
    public function getList(array $param = [])
    {
        // 检索查询条件
        $filter = $this->getFilter($param);
        // 获取分销商订单列表
        $orderList = $this->alias('m')
            ->field('m.*')
            ->join('order', 'order.order_id = m.order_id')
            ->where($filter)
            ->where('m.is_invalid', '=', 0)
            ->where('order.is_delete', '=', 0)
            ->order(['m.create_time' => 'desc'])
            ->paginate(10);
        // 加载关联数据
        return static::preload($orderList, [
            'order' => ['goods.image', 'user.avatar'],
            'dealer_first.user',
            'dealer_second.user',
            'dealer_third.user'
        ]);
    }

    /**
     * 设置检索查询条件
     * @param array $param
     * @return array
     */
    private function getFilter(array $param = []): array
    {
        // 默认参数
        $params = $this->setQueryDefaultValue($param, [
            'searchType' => '',     // 关键词类型 (10订单号 20分销商ID 30会员ID)
            'searchValue' => '',    // 关键词内容
            'settled' => -1,        // 是否已结算佣金
        ]);
        // 检索查询条件
        $filter = [];
        // 是否结算佣金
        $params['settled'] > -1 && $filter[] = ['m.is_settled', '=', (bool)$params['settled']];
        // 关键词
        if (!empty($params['searchValue'])) {
            $searchWhere = [
                10 => ['order.order_no', 'like', "%{$params['searchValue']}%"],
                20 => ['m.first_user_id|m.second_user_id|m.third_user_id', 'like', "%{$params['searchValue']}%"],
                30 => ['m.user_id', '=', (int)$params['searchValue']]
            ];
            array_key_exists($params['searchType'], $searchWhere) && $filter[] = $searchWhere[$params['searchType']];
        }
        return $filter;
    }
}